<template>
  <div class="interview-management-detail-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-section">
      <el-skeleton :rows="8" animated />
    </div>

    <!-- 面试管理详情 -->
    <div v-else class="interview-detail">
      <!-- 头部信息 -->
      <div class="detail-header">
        <div class="header-content">
          <div class="candidate-info">
            <el-avatar :size="60" class="candidate-avatar">
              {{ applicationInfo.candidate_name.charAt(0) }}
            </el-avatar>
            <div class="candidate-details">
              <h1 class="candidate-name">{{ applicationInfo.candidate_name }}</h1>
              <p class="job-title">{{ applicationInfo.job_title }}</p>
              <div class="contact-info">
                <span>{{ applicationInfo.candidate_email }}</span>
                <span>{{ applicationInfo.candidate_phone }}</span>
              </div>
            </div>
          </div>
          <div class="status-info">
            <el-tag 
              :type="getStatusType(applicationInfo.status)"
              size="large"
              class="status-tag"
            >
              {{ getStatusText(applicationInfo.status) }}
            </el-tag>
            <div class="score-info" v-if="applicationInfo.job_fit_score">
              <span class="score-label">匹配度得分</span>
              <span class="score-value">{{ applicationInfo.job_fit_score }}</span>
            </div>
          </div>
        </div>
        
        <div class="header-actions">
          <el-button @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
            返回列表
          </el-button>
          <el-button type="primary" @click="generateReport" v-if="sessionInfo.status === 'completed'">
            <el-icon><Document /></el-icon>
            生成报告
          </el-button>
        </div>
      </div>

      <!-- 面试会话信息 -->
      <div class="session-info-card">
        <div class="card-header">
          <h3>面试会话信息</h3>
        </div>
        <div class="session-details">
          <div class="detail-item">
            <span class="label">面试模板：</span>
            <span class="value">{{ sessionInfo.template_title }}</span>
          </div>
          <div class="detail-item">
            <span class="label">开始时间：</span>
            <span class="value">{{ formatDateTime(sessionInfo.started_at) }}</span>
          </div>
          <div class="detail-item" v-if="sessionInfo.completed_at">
            <span class="label">完成时间：</span>
            <span class="value">{{ formatDateTime(sessionInfo.completed_at) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">面试状态：</span>
            <el-tag :type="getStatusType(sessionInfo.status)">
              {{ getStatusText(sessionInfo.status) }}
            </el-tag>
          </div>
        </div>
      </div>

      <!-- 面试进度 -->
      <div class="progress-card">
        <div class="card-header">
          <h3>面试进度</h3>
        </div>
        <div class="progress-content">
          <div class="progress-stats">
            <div class="stat-item">
              <div class="stat-number">{{ interviewProgress.logical_thinking_score || '-' }}</div>
              <div class="stat-label">逻辑思维得分</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ interviewProgress.answered_video_questions }}/{{ interviewProgress.total_video_questions }}</div>
              <div class="stat-label">视频题目完成</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ overallScore || '-' }}</div>
              <div class="stat-label">综合得分</div>
            </div>
          </div>
          <div class="progress-bar">
            <span class="progress-label">完成进度</span>
            <el-progress 
              :percentage="interviewProgress.is_completed ? 100 : 50" 
              :color="interviewProgress.is_completed ? '#67c23a' : '#e6a23c'"
              :stroke-width="8"
            />
          </div>
        </div>
      </div>

      <!-- 自我介绍视频 -->
      <div class="self-intro-card" v-if="applicationInfo.self_introduction_video">
        <div class="card-header">
          <h3>自我介绍视频</h3>
        </div>
        <div class="video-content">
          <video 
            :src="getVideoUrl(applicationInfo.self_introduction_video)" 
            controls 
            width="100%" 
            height="300"
            class="intro-video"
          >
            您的浏览器不支持视频播放
          </video>
        </div>
      </div>

      <!-- 视频答案列表 -->
      <div class="video-answers-card">
        <div class="card-header">
          <h3>视频答案 ({{ videoAnswers.length }})</h3>
        </div>
        <div class="video-answers-list">
          <div 
            v-for="answer in videoAnswers" 
            :key="answer.id"
            class="video-answer-item"
          >
            <div class="answer-header">
              <div class="question-info">
                <h4 class="question-title">{{ answer.question.title }}</h4>
                <el-tag 
                  :type="getCategoryType(answer.question.category)"
                  size="small"
                  class="category-tag"
                >
                  {{ answer.question.category_display }}
                </el-tag>
              </div>
              <div class="answer-meta">
                <span class="answered-time">{{ formatDateTime(answer.answered_at) }}</span>
              </div>
            </div>
            
            <div class="question-content">
              <p>{{ answer.question.content }}</p>
              <div class="question-details">
                <span class="duration">答题时长：{{ answer.question.answer_duration }}秒</span>
              </div>
            </div>
            
            <div class="answer-content">
              <div class="video-player">
                <video 
                  :src="getVideoUrl(answer.video_url)" 
                  controls 
                  width="100%" 
                  height="240"
                  class="answer-video"
                >
                  您的浏览器不支持视频播放
                </video>
              </div>
              
              <!-- 评分结果 -->
              <div class="scoring-results" v-if="answer.scores">
                <h5>评分结果</h5>
                <div class="score-grid">
                  <div class="score-item" v-if="answer.scores.expression_score">
                    <span class="score-label">表达能力</span>
                    <span class="score-value">{{ answer.scores.expression_score }}</span>
                  </div>
                  <div class="score-item" v-if="answer.scores.innovation_score">
                    <span class="score-label">创新思考</span>
                    <span class="score-value">{{ answer.scores.innovation_score }}</span>
                  </div>
                  <div class="score-item" v-if="answer.scores.professional_skill_score">
                    <span class="score-label">专业技能</span>
                    <span class="score-value">{{ answer.scores.professional_skill_score }}</span>
                  </div>
                  <div class="score-item" v-if="answer.scores.stress_management_score">
                    <span class="score-label">压力应对</span>
                    <span class="score-value">{{ answer.scores.stress_management_score }}</span>
                  </div>
                </div>
              </div>
              
              <!-- 分析结果 -->
              <div class="analysis-results">
                <!-- 音频分析 -->
                <div class="analysis-section" v-if="answer.audio_analysis">
                  <h5>音频分析</h5>
                  <div class="analysis-grid">
                    <div class="analysis-item">
                      <span class="analysis-label">语速</span>
                      <span class="analysis-value">{{ answer.audio_analysis.speech_rate || 0 }} 音节/秒</span>
                    </div>
                    <div class="analysis-item">
                      <span class="analysis-label">音高</span>
                      <span class="analysis-value">{{ answer.audio_analysis.mean_pitch || 0 }} Hz</span>
                    </div>
                    <div class="analysis-item">
                      <span class="analysis-label">音量</span>
                      <span class="analysis-value">{{ answer.audio_analysis.mean_volume || 0 }} dB</span>
                    </div>
                    <div class="analysis-item">
                      <span class="analysis-label">停顿频次</span>
                      <span class="analysis-value">{{ answer.audio_analysis.pause_frequency || 0 }} 次/秒</span>
                    </div>
                    <div class="analysis-item">
                      <span class="analysis-label">修正次数</span>
                      <span class="analysis-value">{{ answer.audio_analysis.correction_frequency || 0 }} 次/秒</span>
                    </div>
                    <div class="analysis-item">
                      <span class="analysis-label">F2轨迹斜率</span>
                      <span class="analysis-value">{{ answer.audio_analysis.f2_slope || 0 }} Hz/ms</span>
                    </div>
                    <div class="analysis-item">
                      <span class="analysis-label">性别识别</span>
                      <span class="analysis-value">{{ getGenderLabel(answer.audio_analysis.gender) }}</span>
                    </div>
                    <div class="analysis-item">
                      <span class="analysis-label">总时长</span>
                      <span class="analysis-value">{{ answer.audio_analysis.speech_duration_seconds?.toFixed(1) || 0 }}秒</span>
                    </div>
                  </div>
                </div>
                
                <!-- 表情分析 -->
                <div class="analysis-section" v-if="answer.expression_analysis">
                  <h5>表情分析</h5>
                  <div class="analysis-grid">
                    <div class="analysis-item">
                      <span class="analysis-label">自信程度</span>
                      <span class="analysis-value">{{ (answer.expression_analysis.overall_emotion_vector.confidence * 100).toFixed(1) }}%</span>
                    </div>
                    <div class="analysis-item">
                      <span class="analysis-label">热情程度</span>
                      <span class="analysis-value">{{ (answer.expression_analysis.overall_emotion_vector.enthusiasm * 100).toFixed(1) }}%</span>
                    </div>
                    <div class="analysis-item">
                      <span class="analysis-label">紧张程度</span>
                      <span class="analysis-value">{{ (answer.expression_analysis.overall_emotion_vector.nervousness * 100).toFixed(1) }}%</span>
                    </div>
                    <div class="analysis-item">
                      <span class="analysis-label">头部姿态</span>
                      <span class="analysis-value">X: {{ answer.expression_analysis.average_head_angle_x.toFixed(1) }}°, Y: {{ answer.expression_analysis.average_head_angle_y.toFixed(1) }}°</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 优秀答案示例 -->
            <div class="excellent-example" v-if="answer.question.excellent_answer_example">
              <el-collapse>
                <el-collapse-item title="查看优秀答案示例" name="example">
                  <p>{{ answer.question.excellent_answer_example }}</p>
                </el-collapse-item>
              </el-collapse>
            </div>
            
            <!-- 评分标准 -->
            <div class="scoring-criteria" v-if="answer.question.scoring_criteria">
              <el-collapse>
                <el-collapse-item title="查看评分标准" name="criteria">
                  <p>{{ answer.question.scoring_criteria }}</p>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="videoAnswers.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无视频答案数据" />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { hrApi } from '@/services/api'
import { 
  ArrowLeft, 
  Document 
} from '@element-plus/icons-vue'

export default {
  name: 'InterviewManagementDetailView',
  components: {
    ArrowLeft,
    Document
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    
    // 响应式数据
    const loading = ref(true)
    const applicationInfo = ref({})
    const sessionInfo = ref({})
    const interviewProgress = ref({})
    const videoAnswers = ref([])
    const overallScore = ref(null)
    
    // 方法
    const goBack = () => {
      router.go(-1)
    }
    
    const generateReport = () => {
      // 生成报告逻辑
      ElMessage.success('报告生成功能待实现')
    }
    
    const formatDateTime = (dateString) => {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString('zh-CN')
    }
    
    const getStatusType = (status) => {
      const typeMap = {
        'pending': 'warning',
        'logic_test': 'primary',
        'video_interview': 'primary',
        'generating_report': 'info',
        'completed': 'success'
      }
      return typeMap[status] || 'info'
    }
    
    const getStatusText = (status) => {
      const textMap = {
        'pending': '待开始',
        'logic_test': '逻辑测试中',
        'video_interview': '视频面试中',
        'generating_report': '生成报告中',
        'completed': '已完成'
      }
      return textMap[status] || '未知状态'
    }
    
    const getCategoryType = (category) => {
      const typeMap = {
        'innovation': 'success',
        'professional': 'primary',
        'pressure': 'warning'
      }
      return typeMap[category] || 'info'
    }
    
    const getVideoUrl = (videoPath) => {
      if (!videoPath) return null
      if (videoPath.startsWith('http')) {
        return videoPath // 已经是完整URL
      }
      return `http://127.0.0.1:8000${videoPath}` // 拼接后端域名
    }
    
    // 加载面试管理数据
    const loadInterviewManagementData = async () => {
      loading.value = true
      try {
        const applicationId = route.params.applicationId
        const response = await hrApi.getInterviewManagement(applicationId)
        
        if (response.success) {
          const data = response.data
          
          // 设置应用信息
          applicationInfo.value = data.application_info
          
          // 设置会话信息
          sessionInfo.value = data.session_info
          
          // 设置面试进度
          interviewProgress.value = data.interview_progress
          
          // 设置视频答案
          videoAnswers.value = data.video_answers || []
          
          // 设置综合得分
          overallScore.value = data.overall_score
          
          console.log('面试管理数据加载成功:', data)
        } else {
          ElMessage.error('加载面试管理数据失败')
        }
      } catch (error) {
        console.error('加载面试管理数据失败:', error)
        ElMessage.error('加载面试管理数据失败，请检查网络连接')
      } finally {
        loading.value = false
      }
    }
    
    onMounted(() => {
      loadInterviewManagementData()
    })
    
    // 获取性别标签
    const getGenderLabel = (gender) => {
      if (gender === 'male') return '男'
      if (gender === 'female') return '女'
      return '未知'
    }
    
    return {
      loading,
      applicationInfo,
      sessionInfo,
      interviewProgress,
      videoAnswers,
      overallScore,
      goBack,
      generateReport,
      formatDateTime,
      getStatusType,
      getStatusText,
      getCategoryType,
      getVideoUrl,
      getGenderLabel
    }
  }
}
</script>

<style scoped>
.interview-management-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.loading-section {
  padding: 20px;
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.detail-header {
  background: white;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.candidate-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.candidate-avatar {
  background: var(--primary-color);
  color: white;
  font-size: 24px;
  font-weight: bold;
}

.candidate-details {
  flex: 1;
}

.candidate-name {
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 4px 0;
}

.job-title {
  font-size: 1rem;
  color: var(--text-secondary);
  margin: 0 0 8px 0;
}

.contact-info {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: var(--text-secondary);
}

.status-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

.score-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.score-label {
  font-size: 12px;
  color: var(--text-secondary);
}

.score-value {
  font-size: 18px;
  font-weight: 600;
  color: var(--primary-color);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.session-info-card,
.progress-card,
.self-intro-card,
.video-answers-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-header {
  margin-bottom: 16px;
}

.card-header h3 {
  margin: 0;
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--text-primary);
}

.session-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-item .label {
  font-weight: 500;
  color: var(--text-secondary);
  min-width: 80px;
}

.detail-item .value {
  color: var(--text-primary);
}

.progress-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.progress-stats {
  display: flex;
  justify-content: space-around;
  text-align: center;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.stat-number {
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--primary-color);
}

.stat-label {
  font-size: 12px;
  color: var(--text-secondary);
}

.progress-bar {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.progress-label {
  font-size: 14px;
  color: var(--text-secondary);
}

.video-content {
  display: flex;
  justify-content: center;
}

.intro-video {
  max-width: 600px;
  border-radius: 8px;
}

.video-answers-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.video-answer-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  background: #fafafa;
}

.answer-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.question-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.question-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.category-tag {
  font-size: 12px;
}

.answer-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.answered-time {
  font-size: 12px;
  color: var(--text-secondary);
}

.question-content {
  margin-bottom: 16px;
}

.question-content p {
  margin: 0 0 8px 0;
  color: var(--text-secondary);
  line-height: 1.6;
}

.question-details {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: var(--text-secondary);
}

.answer-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 16px;
}

.video-player {
  display: flex;
  justify-content: center;
}

.answer-video {
  max-width: 100%;
  border-radius: 8px;
}

.scoring-results,
.analysis-results {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.scoring-results h5,
.analysis-results h5 {
  margin: 0 0 8px 0;
  font-size: 1rem;
  font-weight: 600;
  color: var(--text-primary);
}

.score-grid,
.analysis-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 12px;
}

.score-item,
.analysis-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 8px 12px;
  background: white;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.score-label,
.analysis-label {
  font-size: 12px;
  color: var(--text-secondary);
}

.score-value,
.analysis-value {
  font-size: 14px;
  font-weight: 600;
  color: var(--primary-color);
}

.analysis-section {
  margin-bottom: 16px;
}

.excellent-example,
.scoring-criteria {
  margin-top: 16px;
}

.empty-state {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
  }
  
  .candidate-info {
    flex-direction: column;
    text-align: center;
  }
  
  .status-info {
    align-items: center;
  }
  
  .session-details {
    grid-template-columns: 1fr;
  }
  
  .progress-stats {
    flex-direction: column;
    gap: 16px;
  }
  
  .answer-content {
    grid-template-columns: 1fr;
  }
  
  .score-grid,
  .analysis-grid {
    grid-template-columns: 1fr;
  }
}
</style> 